package com.wfh.easychat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wfh.easychat.annotation.UserCheckLogin;
import com.wfh.easychat.common.BaseResponse;
import com.wfh.easychat.common.ErrorCode;
import com.wfh.easychat.common.ResultUtils;
import com.wfh.easychat.exception.BusinessException;
import com.wfh.easychat.mapper.UserContactMapper;
import com.wfh.easychat.model.entity.GroupInfo;
import com.wfh.easychat.model.entity.UserContact;
import com.wfh.easychat.model.entity.UserInfo;
import com.wfh.easychat.model.enums.GroupJoinTypeEnum;
import com.wfh.easychat.model.request.GroupAddRequest;
import com.wfh.easychat.model.request.GroupUpdateRequest;
import com.wfh.easychat.model.vo.GroupInfoVo;
import com.wfh.easychat.service.GroupInfoService;
import com.wfh.easychat.service.UserContactService;
import com.wfh.easychat.service.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: GroupInfoController
 * @Author wangfenghuan
 * @Package com.wfh.easychat.controller
 * @Date 2025/9/29 20:01
 * @description: 群组控制器
 */
@RestController()
@Slf4j
@RequestMapping("/group")
public class GroupInfoController {

    @Resource
    private GroupInfoService groupInfoService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserContactService userContactService;

    @Resource
    private UserContactMapper userContactMapper;

    /**
     * 群组创建
     *
     * @param groupAddRequest
     * @param avata
     * @return
     */
    @PostMapping(value = "/add")
    @UserCheckLogin
    public BaseResponse<GroupInfoVo> addGroup(@RequestBody GroupAddRequest groupAddRequest, MultipartFile avata, HttpServletRequest request) {
        // 参数校验
        String groupName = groupAddRequest.getGroupName();
        String groupNotice = groupAddRequest.getGroupNotice();
        Integer joinType = groupAddRequest.getJoinType();
        if (StringUtils.isAnyEmpty(groupName, groupNotice)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        GroupJoinTypeEnum enumByValue = GroupJoinTypeEnum.getEnumByValue(joinType);
        GroupInfoVo groupInfoVo = groupInfoService.addGroup(groupName, groupNotice, enumByValue, request, avata);
        return ResultUtils.success(groupInfoVo);
    }

    /**
     * 更新群组信息
     *
     * @param groupUpdateRequest
     * @param request
     * @param newAvata
     * @return
     */
    @PostMapping("/updata")
    @UserCheckLogin
    public BaseResponse<Boolean> updateGroup(@RequestBody GroupUpdateRequest groupUpdateRequest, HttpServletRequest request, MultipartFile newAvata) {
        String groupName = groupUpdateRequest.getGroupName();
        String groupNotice = groupUpdateRequest.getGroupNotice();
        Integer joinType = groupUpdateRequest.getJoinType();
        Integer status = groupUpdateRequest.getStatus();
        GroupJoinTypeEnum enumByValue = GroupJoinTypeEnum.getEnumByValue(joinType);
        // 参数校验
        Long id = groupUpdateRequest.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 调用service
        Boolean res = groupInfoService.updateGroup(status, id, groupName, groupNotice, enumByValue, request, newAvata);
        return ResultUtils.success(res);
    }

    /**
     * 查询当前用户相关联的群组
     * @param request
     * @return
     */
    @UserCheckLogin
    @GetMapping("/getMyGroup")
    public BaseResponse<Page<GroupInfoVo>> getMyGroupList(HttpServletRequest request){
        UserInfo loginUser = userInfoService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = loginUser.getId();
        // 根据用户id查询相关的群组信息
        LambdaQueryWrapper<GroupInfo> queryWrapper = Wrappers.lambdaQuery(GroupInfo.class)
                .eq(GroupInfo::getGroupOwner, id);
        Page<GroupInfo> page = groupInfoService.page(new Page<GroupInfo>(1, 10), queryWrapper);
        List<GroupInfo> records = page.getRecords();
        List<GroupInfoVo> collect = records.stream().map(GroupInfo::objToVo).toList();
        Page<GroupInfoVo> res = new Page<GroupInfoVo>().setRecords(collect).setCurrent(1).setSize(10).setTotal(records.size());
        return ResultUtils.success(res);
    }

    /**
     * 根据群组id获取当前群组信息
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/getById")
    @UserCheckLogin
    public BaseResponse<Map<Object, Object>> getGroupById(Long id, HttpServletRequest request){
        if (id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo loginUser = userInfoService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        GroupInfo byId = groupInfoService.getGroupInfo(id, loginUser);
        long count = userContactService.count(Wrappers.lambdaQuery(UserContact.class)
                .eq(UserContact::getContactId, id));
        HashMap<Object, Object> res = new HashMap<>();
        res.put("groupInfoVo", GroupInfo.objToVo(byId));
        res.put("count", count);
        return ResultUtils.success(res);
    }

    /**
     * 根据id获取群组详情（联系人）
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/getGroupInfoChat")
    @UserCheckLogin
    public BaseResponse<GroupInfoVo> getGroupInfoChat(HttpServletRequest request, Long id){
        // 参数校验
        if (id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo loginUser = userInfoService.getLoginUser(request);
        GroupInfo byId = groupInfoService.getGroupInfo(id, loginUser);
        MPJLambdaWrapper<UserContact> wrapper = new MPJLambdaWrapper<UserContact>()
                .innerJoin(UserInfo.class, UserInfo::getId, UserContact::getId)
                .eq(UserContact::getContactId, id);
        List<UserContact> userContacts = userContactMapper.selectJoinList(wrapper);
        GroupInfoVo groupInfoVo = GroupInfo.objToVo(byId);
        groupInfoVo.setUserContactList(userContacts);
        return ResultUtils.success(groupInfoVo);
    }
}
